import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:seedfour/app/constants.dart';

import '../../../theme.dart';
import 'logic.dart';

class SealCreatePage extends StatelessWidget {
  SealCreatePage({Key? key}) : super(key: key);

  final logic = Get.find<SealCreateLogic>();

  @override
  Widget build(BuildContext context) {
    return Obx(
      () => Scaffold(
        appBar: AppBar(
          title: Text(logic.sealPaperType.value?.label ?? '用印申请'),
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back_ios,
              size: 16.w,
            ),
            onPressed: () {
              Get.back();
            },
          ),
        ),
        body: Form(
          key: logic.formKey,
          child: ListView(
            padding: EdgeInsets.symmetric(horizontal: kSpaceSmall),
            children: [
              SizedBox(height: kSpaceMedium),

              // 关联案件
              if (logic.sealPaperType.value!.value <= 10) ...[
                _buildCaseInfo(),
                SizedBox(height: kSpaceMedium)
              ],

              // 申请内容编辑
              _buildApplyContent(),

              SizedBox(height: kSpaceMedium),

              // 附件上传
              _buildUploadAttachments(),

              SizedBox(height: kSpaceMedium),

              // 提交按钮
              _buildSubmitButton(),

              SizedBox(height: kSpaceMini),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildModuleTitle(String title) {
    return Text(
      title,
      style: TextStyle(fontSize: kFontSizeSmall, color: Colors.grey),
    );
  }

  Widget _buildModuleBg(List<Widget> children) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(kRadiusMedium),
        color: Colors.white,
      ),
      padding: EdgeInsets.all(kSpaceSmall),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: children,
      ),
    );
  }

  Widget _buildSubmitButton() {
    return Container(
      height: 50.w,
      padding: EdgeInsets.symmetric(horizontal: kSpaceSmall),
      child: FilledButton(
        onPressed: () => logic.onSubmit(),
        child: const Text('保存并提交审核'),
      ),
    );
  }

  Widget _buildApplyContent() {
    return _buildModuleBg([
      SizedBox(height: kSpaceMini),

      // 加盖公章选择
      Row(
        children: [
          Text(
            '加盖印章',
            style: TextStyle(
              fontSize: kFontSizeSmall,
              color: AppColor.colorFontBlack,
            ),
          ),
          Expanded(child: SizedBox(width: kSpaceSmall)),
          _buildSelectionBtn('合同章', 1, logic.sealType.value == 1),
          SizedBox(width: kSpaceMedium),
          _buildSelectionBtn('公章', 0, logic.sealType.value == 0),
        ],
      ),

      SizedBox(height: kSpaceSmall),

      // 文件份数输入框
      Row(
        children: [
          Text(
            '文件份数',
            style: TextStyle(
              fontSize: kFontSizeSmall,
              color: AppColor.colorFontBlack,
            ),
          ),
          Expanded(
            child: TextFormField(
              textAlign: TextAlign.end,
              controller: logic.printNumController,
              decoration: InputDecoration(
                hintText: '请输入',
                hintStyle: TextStyle(
                  fontSize: kFontSizeSmall,
                  color: AppColor.colorFontLabelGrey,
                ),
                border: InputBorder.none,
              ),
              keyboardType: TextInputType.number,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '*请输入文件份数';
                }
                // 输入内容为正整数判断
                RegExp reg = RegExp(r'^[1-9]\d*$');
                if (!reg.hasMatch(value)) {
                  return '请输入正整数';
                }
                return null;
              },
            ),
          ),
        ],
      ),

      SizedBox(height: kSpaceMedium),

      Text(
        '备注',
        style: TextStyle(
          fontSize: kFontSizeSmall,
          color: AppColor.colorFontBlack,
        ),
      ),

      // 备注文本输入框
      TextFormField(
        controller: logic.remarkController,
        maxLines: 5,
        decoration: InputDecoration(
          hintText: '邮寄请写明详细地址/需扫描/自取',
          hintStyle: TextStyle(
            fontSize: kFontSizeSmall,
            color: AppColor.colorFontLabelGrey,
          ),
          border: InputBorder.none,
        ),
      ),

      SizedBox(height: kSpaceSmall),
    ]);
  }

  // 上传附件模块
  Widget _buildUploadAttachments() {
    return _buildModuleBg(
      [
        Text(
          '用印文件',
          style: TextStyle(
            fontSize: kFontSizeSmall,
            color: AppColor.colorFontBlack,
          ),
        ),
        SizedBox(height: kSpaceMini),
        if (logic.attachmentNames.isNotEmpty)
          ...List.generate(
            logic.attachmentNames.length,
            (index) => Container(
              padding: EdgeInsets.only(left: kSpaceMedium),
              margin: EdgeInsets.only(top: kSpaceMini),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(kRadiusMedium),
                color: AppColor.colorTagBlue,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Text(
                      logic.attachmentNames[index],
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontSize: kFontSizeSmall,
                        color: AppColor.colorFontBlue,
                        fontWeight: AppFont.fontRegular,
                      ),
                    ),
                  ),
                  IconButton(
                    onPressed: () => logic.deleteFile(index),
                    icon: const Icon(Icons.close, color: Color(0xFFC7C8DB)),
                  ),
                ],
              ),
            ),
          ),
        FilledButton(
          onPressed: () => {logic.pickFile()},
          style: ElevatedButton.styleFrom(
            foregroundColor: AppColor.colorFontBlue,
            backgroundColor: Colors.transparent,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(kRadiusSmall),
            ),
            padding: EdgeInsets.zero,
          ),
          child: Center(
            child: SvgPicture.asset(
              'assets/buttons/ic_upload.svg',
              width: 111.5.w,
              height: 21.w,
            ),
          ),
        ),
      ],
    );
  }

  // 发票类型选择按钮
  Widget _buildSelectionBtn(String title, int selectedValue, bool selected) {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(
          color: selected ? AppColor.colorFontBlue : Colors.transparent,
        ),
        color: selected ? const Color(0xFFF2F3FF) : const Color(0xFFF4F6F9),
        borderRadius: BorderRadius.circular(kRadiusMini),
      ),
      padding: EdgeInsets.symmetric(
        vertical: kSpaceTiny,
        horizontal: kSpaceMini,
      ),
      child: InkWell(
        onTap: () {
          logic.setSelectedSealType(selectedValue);
        },
        child: Text(
          title,
          textAlign: TextAlign.center,
          style: TextStyle(
            color: selected ? AppColor.colorFontBlue : AppColor.colorFontGrey,
            fontSize: kFontSizeSmall,
          ),
        ),
      ),
    );
  }

  Widget _buildCaseInfo() {
    return Obx(() => Ink(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(kRadiusMedium),
            color: Colors.white,
          ),
          child: InkWell(
            onTap: () => _showBottomSheet(),
            borderRadius: BorderRadius.circular(kRadiusMedium),
            child: Padding(
              padding: EdgeInsets.all(kSpaceSmall),
              child: Row(
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '关联案件${logic.selectedCase.value == null ? '' : '（${logic.selectedCase.value!.id}）'}',
                          style: TextStyle(
                            fontSize: kFontSizeSmall,
                            color: AppColor.colorFontBlack,
                          ),
                        ),
                        SizedBox(height: kSpaceTiny),
                        Text(
                          logic.selectedCase.value == null
                              ? '请选择案件'
                              : logic.selectedCase.value!.name,
                          style: TextStyle(
                            fontSize: kFontSizeSmall,
                            color: logic.selectedCase.value == null
                                ? AppColor.colorFontGrey
                                : AppColor.colorFontBlack,
                          ),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(width: kSpaceSmall),
                  Icon(
                    Icons.keyboard_arrow_down,
                    color: AppColor.colorFontBlack,
                    size: 20.w,
                  ),
                ],
              ),
            ),
          ),
        ));
  }

  // 底部关联案件弹窗
  void _showBottomSheet() {
    showModalBottomSheet(
      backgroundColor: Colors.white,
      context: Get.context!,
      isDismissible: false,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(15.w)),
      ),
      builder: (context) {
        return SizedBox(
          width: double.infinity,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Padding(
                padding: EdgeInsets.only(
                  left: kSpaceMedium,
                  top: kSpaceTiny,
                  bottom: kSpaceTiny,
                  right: kSpaceTiny,
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '请选择关联案件',
                      style: TextStyle(
                        fontSize: kFontSizeMedium,
                        color: AppColor.colorFontBlack,
                      ),
                    ),
                    IconButton(
                      onPressed: () => {Get.back()},
                      icon: SvgPicture.asset(
                        'assets/icons/ic_cancel_black.svg',
                        width: kIconSizeMini,
                      ),
                    ),
                  ],
                ),
              ),
              const Divider(),
              Expanded(
                child: ListView.builder(
                  itemCount: logic.caseList.length,
                  itemBuilder: (context, index) {
                    return ListTile(
                      title: Text(
                        logic.caseList[index].name,
                        style: TextStyle(
                          fontSize: kFontSizeSmall,
                          color: AppColor.colorFontBlack,
                        ),
                      ),
                      subtitle: Text(
                        logic.caseList[index].caseDate,
                        style: TextStyle(
                          fontSize: kFontSizeMini,
                          color: AppColor.colorFontGrey,
                        ),
                      ),
                      trailing: Obx(
                        () => logic.selectedCase.value == logic.caseList[index]
                            ? SvgPicture.asset(
                                'assets/icons/ic_radio_selected.svg',
                                width: 16.w)
                            : SvgPicture.asset(
                                'assets/icons/ic_radio_unselect.svg',
                                width: 16.w),
                      ),
                      onTap: () => logic.onSelectCase(logic.caseList[index]),
                    );
                  },
                ),
              ),
              const Divider(),
              Padding(
                padding: EdgeInsets.all(kSpaceMedium),
                child: Row(
                  children: [
                    Expanded(
                      child: FilledButton(
                        onPressed: () => logic.onCreateCase(),
                        child: Container(
                          alignment: Alignment.center,
                          height: 50.w,
                          child: Text(
                            '创建案件',
                            textAlign: TextAlign.center,
                            style: TextStyle(fontSize: kFontSizeMedium),
                          ),
                        ),
                      ),
                    ),
                    SizedBox(width: kSpaceMedium),
                    Expanded(
                      child: Obx(
                        () => FilledButton(
                          onPressed: logic.selectedCase.value == null
                              ? null
                              : () => {Get.back()},
                          child: Container(
                            alignment: Alignment.center,
                            height: 50.w,
                            child: Text(
                              '确认',
                              textAlign: TextAlign.center,
                              style: TextStyle(fontSize: kFontSizeMedium),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}
